/**
 * @(#)RetentFileTimer.java 2017年02月27日
 * Copyright(C) 2017 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.timer;

import java.util.HashMap;
import java.util.Map;

import org.jsbd.boss.domian.channel.ThirdSmsSyncVo;
import org.jsbd.boss.httpclient.HttpClientUtil;
import org.jsbd.boss.httpclient.vo.Request;
import org.jsbd.boss.httpclient.vo.Response;
import org.jsbd.boss.util.CacheKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;

/**
 * 第三方短信验证码回调
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
@Service
public class ThirdSmsCallBackTimer extends TaskAdapterHandler {
	public static final Logger LOGGER = LoggerFactory.getLogger(ThirdSmsCallBackTimer.class);

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jsbd.boss.timer.TaskHandler#execute()
	 */
	@Override
	public void run() {
			String lockKey = CacheKey.THIRD_SMS_CALLBACK_LIST + "_LOCK";
			if (redisClient.evalSetNx(lockKey, 3)) {
				for (int i = 0; i < 100; i++) {
					ThirdSmsSyncVo smsSyncVo = (ThirdSmsSyncVo) redisClient.pollFromQueue(CacheKey.THIRD_SMS_CALLBACK_LIST);
					if (smsSyncVo == null) {
						return;
					}
					String url = smsSyncVo.getCallbackUrl();
					if (url.indexOf("?") > 0) {
						url = url.substring(0, url.indexOf("?"));
					}
					Request request = new Request();
					Map<String, String> params = new HashMap<String, String>();
					params.put("smsCode", smsSyncVo.getSmsCode());
					params.put("bizId", smsSyncVo.getCode());
					params.put("imsi", smsSyncVo.getImsi());
					params.put("mobile", smsSyncVo.getMobile());
					params.put("provinceId", smsSyncVo.getProvinceId().toString());
					request.setParams(params);
					request.setUrl(url);
					request.setTimeout(3000);
					//超时重试
					int retryCount = 3;
					while(retryCount > 0){
						try {
							Response response = HttpClientUtil.doGet(request);
							if(response != null && response.isSuccess()){
								retryCount = -1;
							}
						} catch (Exception e) {
							LOGGER.error("回调接口出错", e);
							retryCount--;
						}
					}
					LOGGER.warn("回调 {} {} ", url, JSONObject.toJSONString(params));
				}
			}
	}

}
